<?php
/**
 * 可以处理所有的跨域请求包括 credentials 类型（带cookie的）
 *
 * Created by PhpStorm.
 * Author: Zeon
 * Date: 2018/3/21
 * Created by Panxsoft.
 */
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use function EasyWeChat\Kernel\data_get;

class Cors
{
    public function handle(Request $request, Closure $next)
    {
        $allow_origin = $request->header('Origin');

        $response = $next($request);
        if ($response instanceof Response) {
            return $this->responseWithHeaders($response, $allow_origin);
        } else {
            // 这里在 EasyWechat 的重定向类改了？只能使用原生的
            $this->setPhpHeaders($allow_origin);

            return $response;
        }
    }

    /**
     * @param $allow_origin
     */
    private function setPhpHeaders($allow_origin): void
    {
        header("Access-Control-Allow-Origin: {$allow_origin}");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization, Accept, Application, X-Requested-With");
    }

    /**
     * @param $response
     * @param $allow_origin
     * @return mixed
     */
    private function responseWithHeaders(Response $response, $allow_origin)
    {
        return $response
            ->withHeaders([
                'Access-Control-Allow-Origin'      => $allow_origin,
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Methods'     => 'GET, PUT, POST, DELETE, OPTIONS',
                'Access-Control-Allow-Headers'     => 'Content-Type, X-Auth-Token, Origin, Authorization, Accept, Application, X-Requested-With'
            ]);
    }


}